package com.example.spring.exercise.controller;

import com.example.spring.exercise.service.CheckService;
import com.example.spring.exercise.service.dto.check.ClassCheckAbsentDTO;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.springframework.cache.CacheManager;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;

/**
 * @author : zhayh
 * @date : 2021-5-22 20:15
 * @description :
 */

@RestController
@RequestMapping("/api")
public class Unit8Controller {
    @Resource
    private CacheManager cacheManager;
    @Resource
    private CheckService checkService;

    // http://localhost:8080/api/check/class-absent?className=%E7%A7%BB%E5%8A%A81923&termNo=20200
    @GetMapping("/check/class-absent")
    @ApiOperation(value = "获取班级缺勤与部门比率")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "className", value = "班级名称", dataTypeClass = String.class),
            @ApiImplicitParam(name = "termNo", value = "年级", dataTypeClass = String.class)
    })
    public ResponseEntity getClassCheckAbsent(@RequestParam("className") String className,
                                              @RequestParam("termNo") String termNo) {
        long time0 = System.currentTimeMillis();
        ClassCheckAbsentDTO result =  checkService.getClassCheckAbsent(className, termNo);
        long time1 = System.currentTimeMillis();
        result.setTotalTime(time1 - time0);
        return ResponseEntity.ok(result);
    }

    @DeleteMapping("/check/class-absent")
    @ApiOperation(value = "使用缓存框架实现缓存回收")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "className", value = "班级名称", dataTypeClass = String.class),
            @ApiImplicitParam(name = "termNo", value = "年级", dataTypeClass = String.class)
    })
    public ResponseEntity deleteClassCheckAbsentCaches(@RequestParam("className") String className,
                                                       @RequestParam("termNo") String termNo) {
        String key = className + "-" + termNo;
        cacheManager.getCache("system-absent").evictIfPresent(key);
        return ResponseEntity.ok("缓存清除完成");
    }

}
